<script setup lang="ts">
import { ref } from "vue";
import { ElDialog, ElInput, ElMessageBox } from "element-plus";
import ProFormMax from "@/modules/package/form/components/ProFormMax.vue";

import regMenu from "@/utils/reg";
import ApiUsers from "@/api/users";
import useApp from "@/store/useApp";
import appToken from "@/utils/appToken";

const formSchema = [
  {
    label: "旧密码",
    children: {
      type: ElInput,
      field: "password",
      props: {
        type: "password",
        showPassword: true,
        placeholder: "至少6位数字与字母组合密码",
      },
    },
  },

  {
    label: "密码",
    children: {
      type: ElInput,
      field: "new_password",
      props: {
        type: "password",
        showPassword: true,
        placeholder: "至少6位数字与字母组合密码",
      },
    },
  },

  {
    label: "确认密码",
    children: {
      type: ElInput,
      field: "confirmPassword",
      props: { type: "password", showPassword: true, placeholder: "再次输入密码" },
    },
  },
];

const stateApp = useApp();

const refForm = ref();
const model = ref<any>({
  password: "",
  new_password: "",
  confirmPassword: "",
});

const visible = defineModel<boolean>();

// 验证密码
const validatePass = (_: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入确认密码"));
  } else if (value !== model.value.new_password) {
    callback(new Error("两次密码输入不一致"));
  } else {
    callback();
  }
};

const rules = {
  password: [
    { required: true, message: "请输入密码" },
    { pattern: regMenu.password, message: "密码至少6位数字和字母的组合" },
  ],
  new_password: [
    { required: true, message: "请输入新密码" },
    { pattern: regMenu.password, message: "密码至少6位数字和字母的组合" },
  ],

  confirmPassword: [
    { required: true, message: "请输入确认密码" },
    { validator: validatePass },
  ],
};

const service: any = [
  ApiUsers.updatePwd,
  {
    defaultModel: model,
    formatModel(res: any) {
      const data = { ...res };
      Reflect.deleteProperty(data, "confirmPassword");
      return data;
    },
  },
];

// 表单提交成功
const handleSuccess = async () => {
  appToken.cleartToken();
  await ElMessageBox.alert("密码修改成功，请重新登录", "提示", {
    showClose: false,
  });
  stateApp.logout(true);
};
</script>

<template>
  <ElDialog
    v-model="visible"
    title="修改密码"
    width="420"
    destroy-on-close
    @closed="refForm.reset()"
  >
    <ProFormMax
      ref="refForm"
      :col="24"
      :rules="rules"
      :service="service"
      :form-items="formSchema"
      @success="handleSuccess"
      label-width="6em"
    />
  </ElDialog>
</template>
